package com.bawei.lib_common.weiget

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import kotlinx.coroutines.MainScope

/**
 *作者：lxy
 *功能:
 *时间：2025/6/15
 */
class RichEditText : AppCompatEditText {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    val tools: MutableList<Tool> = mutableListOf()
    private var mEditable = true
    private var mIncrease = false

    private val mMainScope by lazy {
        MainScope()
    }

    //插入的图片key-path value-url
    private val mImagePath2UrlMap = mutableMapOf<String, String>()

    private var mTextWatcher: TextWatcher = object : TextWatcher {
        var inputStart = 0
        var inputEnd = 0
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            inputStart = start
            inputEnd = start + count
            mIncrease = inputStart < inputEnd
        }

        override fun afterTextChanged(s: Editable) {
            if (mEditable) {
                if (inputEnd > inputStart) {
                    for (tool in tools) {
                        tool.applyStyle(inputStart, inputEnd)
                    }
                }
            }
        }
    }
}


abstract class Tool {
    var editText: RichEditText? = null
    protected var styleEnable: Boolean = false

    abstract fun applyStyle(start: Int, end: Int)

    abstract fun onSelectionChanged(selStart: Int, selEnd: Int)
}